package com.kye.express.business.jd.after_sale.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.jd.after_sale.JDAfterSaleMainActivity;
import com.kye.express.business.jd.after_sale.viewbinder.JDAfterSaleTypeTagsViewBinder;
import com.kye.express.business.jd.order_detail.model.JDOrderDetailModel;
import com.kye.express.databinding.FragmentJdAfterSaleApplyBinding;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.jd.order_details.JDGoodsAfterSaleTypeBean;
import com.kye.model.bean.user.User;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 08/02/2018
 * @updated : 08/02/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class JDAfterSaleApplyFragment extends BaseAppCompatFragment implements JDAfterSaleApplyConstract.JDAfterSaleApplyView, JDAfterSaleTypeTagsViewBinder.OnTagsItemListener {

    private final static String TAG_DATA = "TAG_DATA";
    private final static String TAG_SELECTED_AFTER_SALE_TYPE = "TAG_SELECTED_AFTER_SALE_TYPE";
    private JDOrderDetailModel orderDetailModel;
    private User userInfo;
    private MultiTypeAdapter adapter;
    private FragmentJdAfterSaleApplyBinding binding;
    private JDAfterSaleApplyConstract.JDAfterSaleApplyPresenter presenter;
    private JDGoodsAfterSaleTypeBean selectedAfterSaleType;

    public static JDAfterSaleApplyFragment newInstance(JDOrderDetailModel orderDetailModel) {
        Bundle args = new Bundle();
        args.putParcelable(TAG_DATA, orderDetailModel);
        JDAfterSaleApplyFragment fragment = new JDAfterSaleApplyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            orderDetailModel = getArguments().getParcelable(TAG_DATA);
        } else {
            orderDetailModel = savedInstanceState.getParcelable(TAG_DATA);
            selectedAfterSaleType = savedInstanceState.getParcelable(TAG_SELECTED_AFTER_SALE_TYPE);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jd_after_sale_apply, container, false);
        presenter = new JDAfterSaleApplyConstract.JDAfterSaleApplyPresenter();
        initViews(view);
        initEvents(view);
        return view;
    }

    private void initViews(View view) {
        binding = DataBindingUtil.bind(view);
        ChipsLayoutManager spanLayoutManagerHot = ChipsLayoutManager.newBuilder(getActivity())
                .setOrientation(ChipsLayoutManager.HORIZONTAL)
                .build();
        adapter = new MultiTypeAdapter();
        adapter.register(JDGoodsAfterSaleTypeBean.class, new JDAfterSaleTypeTagsViewBinder(this));
        binding.afterSaleTypes.setLayoutManager(spanLayoutManagerHot);
        binding.afterSaleTypes.setAdapter(adapter);
    }

    private void initEvents(View view) {
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.next)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (chechInput()) {
                            JDAfterSaleMainActivity afterSaleMainActivity = (JDAfterSaleMainActivity) getActivity();
                            afterSaleMainActivity.toSubmitPage(orderDetailModel, selectedAfterSaleType, binding.descriptions.getText().toString());
                        }
                    }
                });
        RxTextView.textChanges(binding.descriptions)
                .compose(bindToLifecycle())
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        String content = charSequence.toString();
                        int length = content.length();
                        binding.textSizeLeft.setText(length + "/500");
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.getAfterSaleTypes(orderDetailModel, userInfo);
            }
        });
    }

    private boolean chechInput() {
        if (selectedAfterSaleType == null) {
            ToastManager.show(getActivity(), "请选择服务类型");
            return false;
        } else if (TextUtils.isEmpty(binding.descriptions.getText().toString())) {
            ToastManager.show(getActivity(), "请选输入问题描述");
            return false;
        }
        return true;
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        presenter.bind(this);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putParcelable(TAG_DATA, orderDetailModel);
        outState.putParcelable(TAG_SELECTED_AFTER_SALE_TYPE, selectedAfterSaleType);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        binding.statusLayout.showLoadingView();
    }

    @Override
    public void getAfterSaleTypesSuccess(List<JDGoodsAfterSaleTypeBean> jdGoodsAfterSaleTypeBeans) {
        binding.statusLayout.showContentView();
        binding.setData(orderDetailModel);
        Double integralTaken = Double.parseDouble(orderDetailModel.getIntegralTaken());
        if (integralTaken > 10000) {
            binding.integralTaken.setText("消耗积分: " + String.format("%.2f", integralTaken / 10000.0) + "万");
        } else {
            binding.integralTaken.setText("消耗积分: " + String.format("%.2f", integralTaken));
        }
        updateAfterSaleType(selectedAfterSaleType, jdGoodsAfterSaleTypeBeans);
    }

    private void updateAfterSaleType(JDGoodsAfterSaleTypeBean selectedAfterSaleType, List<JDGoodsAfterSaleTypeBean> jdGoodsAfterSaleTypeBeans) {
        if (selectedAfterSaleType == null) {
            adapter.setItems(jdGoodsAfterSaleTypeBeans);
            adapter.notifyDataSetChanged();
            return;
        }
        Observable.fromIterable(jdGoodsAfterSaleTypeBeans)
                .doOnNext(new Consumer<JDGoodsAfterSaleTypeBean>() {
                    @Override
                    public void accept(JDGoodsAfterSaleTypeBean jdGoodsAfterSaleTypeBean) throws Exception {
                        if (jdGoodsAfterSaleTypeBean.equals(selectedAfterSaleType)) {
                            jdGoodsAfterSaleTypeBean.setSelected(selectedAfterSaleType.isSelected());
                            JDAfterSaleApplyFragment.this.selectedAfterSaleType = jdGoodsAfterSaleTypeBean;
                        }
                    }
                })
                .any(new Predicate<JDGoodsAfterSaleTypeBean>() {
                    @Override
                    public boolean test(JDGoodsAfterSaleTypeBean jdGoodsAfterSaleTypeBean) throws Exception {
                        return jdGoodsAfterSaleTypeBean.isSelected();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (!aBoolean) {
                            JDAfterSaleApplyFragment.this.selectedAfterSaleType = null;
                        }
                        adapter.setItems(jdGoodsAfterSaleTypeBeans);
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    public void getAfterSaleTypesNetFailed(String msg) {
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void getAfterSaleTypesServerFailed(String message) {
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void onTagClicked(JDGoodsAfterSaleTypeBean item) {
        this.selectedAfterSaleType = item;
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoaded() {

    }

}
